<?php class Model_corrector extends Model {
    function Model_corrector() {
        parent::Model();
        $this->fromSession = $this->usersession->currentUser();
    }

    function bringObject($table, $s_limit, $e_limit, $sort, $dir, $where) {

        $result = array();

        if (($table == 'domain') || ($table == 'position')) {
           
           //se iau toate datele
            $this->db->select(" t2.name as obj,t2.level,t2.{$table}_id as id,t2.update_date  ", false);
            $this->db->join(" {$table} AS t2   ", "t2.parent_id = {$table}.{$table}_id ", "inner");
            $this->db->order_by("{$table}.name", 'asc');
            $this->db->order_by("{$table}.{$table}_id", 'asc');
            $this->db->order_by("t2.level", 'asc');
            $this->db->order_by('t2.name', 'asc');

            $query = $this->db->get($table);
            $result = $query->result_array();
            $totalCount = $this->db->count_all_results();

            //aflare cate contacte sunt pe fiecare obiect
            $countEach = $this->db->query("select count(person_id) as nr,{$table}_id from persons  group by {$table}_id");
            foreach($countEach->result_array() as $row) {
                //fac un array de genul  city_id=> nr
                $countArray[$row[$table."_id"]] = $row['nr'];
            }

            //aflare cate contacte sunt pe fiecare subobiect 
            $countEachSub = $this->db->query("select count(person_id) as nr,{$table}_sub_id from persons  group by {$table}_sub_id");
            foreach($countEachSub->result_array() as $row) {
                //fac un array de genul  city_id=> nr
                $countArraySub[$row[$table."_sub_id"]] = $row['nr'];
            }

            foreach($result as $key =>$data) {
                
                //scot countul pentru fiecare obiect sau subobiect
                if ($data['level'] == 0) {
                    $count = $countArray[$data['id']];
                    if ($count == '') $count = 0;
                } else {
                    $count = $countArraySub[$data['id']];
                    if ($count == '') $count = 0;
                }
                //pentru fiecare obiect, subobiect atasez countul de contacte                     
                $result[$key]['count'] = $count;

                //daca se face filtrare dupa nume atunci urm reguli se aplica :
                // daca obiectul contine textul atunci se aduc toate obiectele
                // daca un subiect contine textul atunci se aduce si obiectul
                //din totalul de obiecte -subobiecte obtinute se filtreaza cele care nu corespund regulii de mai sus
                if ($where['name'] != '') {

                    $data["count"] = $count;

                    if ($data['level'] == '0') {
                        $parent = $data;
                        //initializez o varibila bool care imi spune daca s-a inclus in array-ul final si parintele
                        $parent_included = false;
                        //initializez o varibila bool care imi spune daca s-a gasit textul in obiect
                        $parent_search = false;
                    }
                    //caut in obiect textul  
                    if ((stripos($data['obj'], $where['name']) !== false) && (!$parent_included) && ($data['level'] == '0')) {
                        $temp[] = $data;
                        $parent_included = true;
                        $parent_search = true;
                    }
                    //daca in parinte s-a gasit textul atunci parintele va fi atasat in array-ul final
                    if ($parent_search) {
                        $temp[] = $data;
                    }
                    //daca nu se gaseste atunci cautarea are loc la nivel de subobiect
                    else {
                        //daca in subobiect se gaseste textul atunci in functie de $parent_included se adauga sau nu obiectul
                        if ((stripos($data['obj'], $where['name']) !== false) && (!$parent_included) && ($data['level'] == '1')) {
                            $temp[] = $parent;
                            $temp[] = $data;
                            $parent_included = true;
                        }

                        if ((stripos($data['obj'], $where['name']) !== false) && ($parent_included) && ($data['level'] == '1')) {
                            $temp[] = $data;
                            $parent_included = true;
                        }
                    }
                    $result = $temp;
                }
            }
        }
        else
        {
            //se scot toate datele
            $this->db->select(" {$table}.name as obj,{$table}_id as id,{$table}.update_date,level ", false);
            $this->db->order_by("{$table}.name", 'asc');

            //se cauta in nume daca s-a introdus filtrarea  
            if ($where['name'] != '') {
                $this->db->like("{$table}.name", $where['name']);
            }

            $query = $this->db->get($table);
            $result = $query->result_array();
            $totalCount = $this->db->count_all_results();

            //aflare cate contacte sunt pe fiecare obiect
            $countEach = $this->db->query("select count(person_id) as nr,{$table}_id from persons  group by {$table}_id");
            foreach($countEach->result_array() as $row) {
                //fac un array de genul  city_id=> nr
                $countArray[$row[$table."_id"]] = $row['nr'];
            }
            //daca au fost gasite inregistrari
            if ($query->num_rows()) {
                foreach($result as $key =>$data) {
                    //aflu contul de contacte pentru obiectul respectiv
                    $count = $countArray[$result[$key]['id']];
                    if ($count == '') $count = 0;
                      // in fiecare obiect atasez si countul de contacte
                    $result[$key]['count'] = $count;                   
                }
            } else $result = array();

        }

        $data = array('totalCount' =>$totalCount, 'DS_OBJECT' =>$result);
        return $data;
    }
    
    function editObject($data) {

        $this->db->where($data['table']."_id", $data['id']);
        $this->db->set("name", strTitle($data['name']));
        $this->db->set("created_by",  $this->fromSession["user_id"]);
        $query = $this->db->update($data['table']);

        if ($query) $aResponse = array("description" =>"Datele au fost salvate", "success" =>true);
        else $aResponse = array("description" =>"Datele NU au fost salvate", "success" =>false);

        return $aResponse;
    }

    function delete($data) {

        $table = $data['table'];
        //se decodifica array-ul JSON care contine id si level-ul asociat obiectului trimis
        $primeValues = json_decode($data['primeValues']);

        foreach($primeValues as $obj) {
            //scot datele sa aflu daca este obiect sau subobiect
            $this->db->flush_cache();
            $query = $this->db->get_where($table, array($table."_id" =>$obj->id));
            $result = $query->row_array();
           
            //daca obiectul trimis este parinte atunci toti copii tb stersi
            if ($result["level"] == 0) {
                //sterg parintele
                $this->db->flush_cache();
                $this->db->where($table."_id", $result[$table."_id"]);
                $this->db->delete($table);

                //sterg toti copii
                if (($table == "position") || ($table == "domain")) {
                    $this->db->flush_cache();
                    $this->db->where("parent_id", $result[$table."_id"]);
                    $this->db->delete($table);
                }

                //resetez pe contact valoarea obiectului
                $this->db->flush_cache();
                $this->db->set($table."_id", "");

                if (($table == "position") || ($table == "domain"))
                $this->db->set($table."_sub_id", "");

                $this->db->where($table."_id", $result[$table."_id"]);
                $this->db->update("persons");
            }

            //daca este subobiect
            if ($result["level"] == 1) {
                //sterg parintele
                $this->db->flush_cache();
                $this->db->where($table."_id", $result[$table."_id"]);
                $this->db->delete($table);
                //resetez pe contact valoarea obiectului
                $this->db->flush_cache();
                $this->db->set($table."_sub_id", "");
                $this->db->where($table."_sub_id", $result[$table."_id"]);
                $this->db->update("persons");
            }

        }

        $aResponse = array("description" =>"Datele au fost salvate", "success" =>true);
        return $aResponse;

    }

    function transfer($data) {

        $table = $data['table'];
        $finalValue =$data['finalValue'];    
        $primeValues = json_decode($data['primeValues']);
        

        if ($finalValue == '') {
            $aResponse = array("description" =>"Lipseste data de destinatie", "success" =>false);
            return $aResponse;
        }

        if (count($primeValues) == 0) {
            $aResponse = array("description" =>"Lipseste data de transfer", "success" =>false);
            return $aResponse;
        }
        
        //scot nivelul obiectului destinatie
        $query = $this->db->get_where("{$table}", array($table."_id" =>$finalValue));
        $iLevelFinal = $query->row()->level;

        if (($table == "domain") || ($table == "position")) {
            
            //cauta sa vad daca sunt numai obiecte sau numai sub-obiecte
            //initializez doua variabile bool prin care aflu daca s-au trimis si parinti si copii din gridul S
            $bSubObject = FALSE;
            $bObject = FALSE;
            
            foreach($primeValues as $key =>$val) {
                
                $this->db->flush_cache();
                $query = $this->db->get_where("{$table}", array($table."_id" =>$val->id));
                $iLvl = $query->row()->level;

                if ($iLvl == "0") {
                    $bObject = TRUE;
                    
                    //daca se trimite un parinte caut sa vad daca exista si copii pe acel parinte
                    //regula de transfer este ca sa se trimita un parinte care nu are copii
                    $this->db->flush_cache();
                    $this->db->where("level", "1");
                    $query = $this->db->get_where("{$table}", array("parent_id" =>$val->id));
                    if ($query->num_rows() > 0) {
                        $aResponse = array("description" =>"Obiectul are copii ! Eliminati mai intai subobiectele si apoi reluati operatia !", "success" =>false);
                        return $aResponse;
                    }
                }
                if ($iLvl == "1") {
                    $bSubObject = TRUE;                    
                }
            }
        } 
        //daca se trimit si parinti si copii se da mesaj si se opreste functia
        if (($bObject === TRUE) && ($bSubObject === TRUE)) {
            $aResponse = array("description" =>"Alegeti numai obiecte sau numai subobiecte !!", "success" =>false);
            return $aResponse;
        }

        foreach($primeValues as $key =>$val) {
            $this->db->flush_cache();
            $query = $this->db->get_where("{$table}", array($table."_id" =>$val->id));
            $resultPrime = $query->row_array();
            $dataPrime[] = $resultPrime;
        }

        if ($iLevelFinal == '1'){
            foreach($dataPrime as $val) {
                if (($val['level'] == '1') && ($val[$table."_id"] != $finalValue))
                        $this->_trans11Object($val, $finalValue, $table);
                if (($val['level'] == '0') && ($val[$table."_id"] != $finalValue))
                        $this->_trans01Object($val, $finalValue, $table);
            }
        }

        if ($iLevelFinal == '0'){
            foreach($dataPrime as $val) {
                if ($val['level'] == '1')
                        $this->_trans10Object($val, $finalValue, $table);
                if (($val['level'] == '0') && ($val[$table."_id"] != $finalValue))
                        $this->_trans00Object($val, $finalValue, $table);
            }
        }

        $aResponse = array("description" =>"Datele au fost salvate", "success" =>true);
        return $aResponse;
    }

    function _trans11Object($dataPrime, $dataFinal, $table) {
        //extrag datele subobiectului
        $query = $this->db->get_where("{$table}", array($table."_id" =>$dataFinal));
        $temp = $query->row_array();

        $this->db->flush_cache();
        $this->db->set($table."_sub_id", $dataFinal);
        $this->db->set($table."_id", $temp['parent_id']);
        $this->db->where($table."_sub_id", $dataPrime[$table."_id"]);
        $this->db->update('persons');

        $this->db->flush_cache();
        $this->db->where($table."_id", $dataPrime[$table."_id"]);
        $this->db->delete($table);
    }

    function _trans10Object($dataPrime, $dataFinal, $table) {
        $this->db->flush_cache();
        $this->db->set("parent_id", $dataFinal);
        $this->db->where($table."_id", $dataPrime[$table."_id"]);
        $this->db->update($table);

        //update pe persoane
        $this->db->flush_cache();
        $this->db->set($table."_id", $dataFinal);
        $this->db->where($table."_sub_id", $dataPrime[$table."_id"]);
        $this->db->update("persons");
    }

    function _trans01Object($dataPrime, $dataFinal, $table) {

        $this->db->flush_cache();
        $this->db->where($table."_id", $dataPrime[$table."_id"]);
        $this->db->delete($table);

        //extrag datele subobiectului
        $query = $this->db->get_where("{$table}", array($table."_id" =>$dataFinal));
        $temp = $query->row_array();

        //update pe persoane
        $this->db->flush_cache();
        $this->db->set($table."_sub_id", $dataFinal);
        $this->db->set($table."_id", $temp['parent_id']);
        $this->db->where($table."_id", $dataPrime[$table."_id"]);
        $this->db->update("persons");
    }

    function _trans00Object($dataPrime, $dataFinal, $table) {
        $this->db->flush_cache();
        $this->db->where($table."_id", $dataPrime[$table."_id"]);
        $this->db->delete($table);

        //update pe persoane
        $this->db->flush_cache();
        $this->db->set($table."_id", $dataFinal);
        $this->db->where($table."_id", $dataPrime[$table."_id"]);
        $this->db->update("persons");
    }

} //end model
